#include "apue.h"
#include <wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

static volatile sig_atomic_t sigflag;   /* set nonzero by sig handler (pid 0, child 1) */
static sigset_t newmask, oldmask, zeromask;
static void charatatime(char *str);

int main(void) {
    pid_t pid;
    TELL_WAIT();

    setbuf(stdout, NULL);
    if ((pid= fork()) < 0) 
        err_sys("fork error");
    else if (pid == 0) {
        charatatime("child: hello word\n");
        TELL_PARENT(getppid());
        exit(0);
    }
    WAIT_CHILD();
    charatatime("parent: hello word\n");
    if (waitpid(pid, NULL, 0) < 0)
        err_sys("waitpid error");
    exit(0);
}

static void sig_usr(int signo) {
    sigflag= 1;
}

void TELL_WAIT(void) {
    if (signal(SIGUSR1, sig_usr))
        err_sys("signal(SIGUSR1) error");
    if (signal(SIGUSR2, sig_usr))
        err_sys("signal(SIGUSR2) error");
    sigemptyset(&newmask);
    sigemptyset(&zeromask);
    sigaddset(&newmask, SIGUSR1);
    sigaddset(&newmask, SIGUSR2);

    if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)
        err_sys("SIG_BLOCK error");
}

void WAIT_PARENT(void) {
    while (sigflag != 1) 
        sigsuspend(&zeromask);
    sigflag= 0;

    if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
        err_sys("SIG_SETMASK error");
}

void TELL_PARENT(pid_t ppid) {
    kill(ppid, SIGUSR1);
}

void WAIT_CHILD(void) {
    while (sigflag != 1) 
        sigsuspend(&zeromask);
    sigflag= 0;

    if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
        err_sys("SIG_SETMASK error");
}

void TELL_CHILD(pid_t pid) {
    kill(pid, SIGUSR2);
}

static void charatatime(char *str) {
    setbuf(stdout, NULL);   /* set unbuffered */
    struct timespec tv;

    tv.tv_sec= 0;
    tv.tv_nsec= 1000 * 1000;

    while (*str != 0) {
        putchar(*str++);
        nanosleep(&tv, NULL);
    }
}

